import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'

Vue.use(Router)

const router = new Router({
	routes,
	mode: 'history'
})

// 获取原型对象上的push函数
const originalPush = Router.prototype.push
// 修改原型对象中的push方法
Router.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {

	//如果未匹配到路由
	if (to.matched.length === 0) {
		// 如果from能匹配到则转from路由 如果form也未匹配到路由则跳转login
		from.name ? next({
			name: from.name
		}) : next('/login');
	} else {
		// window.console.log(from.name);
		// window.console.log(to.name);
		next();
	}
});

export default router
